package org.mixare.gui;

import org.mixare.R;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;


public class Register extends Activity {

	
	private TextView errMsg;
	private EditText firstEdit, lastEdit, loginEdit, passEdit, pass2Edit, fbEdit;
	private String login, pass, pass2, fb;

	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		setContentView(R.layout.register);

		errMsg = (TextView) findViewById(R.id.reg_error_msg);

		firstEdit = (EditText) findViewById(R.id.reg_edit_firstname);
		lastEdit = (EditText) findViewById(R.id.reg_edit_lastname);
		loginEdit = (EditText) findViewById(R.id.reg_edit_username);
		passEdit = (EditText) findViewById(R.id.reg_edit_password);
		pass2Edit = (EditText) findViewById(R.id.reg_edit_password2);
		fbEdit = (EditText) findViewById(R.id.reg_edit_fb_profile);

		Button create = (Button) findViewById(R.id.reg_create);
		create.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				if(firstEdit == null || lastEdit == null || loginEdit == null || 
						fbEdit == null || passEdit == null || pass2Edit == null){
					errMsg.setText(R.string.required);
				}else{
					login = loginEdit.getText().toString();
					pass = passEdit.getText().toString();
					pass2 = pass2Edit.getText().toString();
					fb = fbEdit.getText().toString();
					if(login.equals("") || pass.equals("") || pass2.equals("")){
						errMsg.setText(R.string.required);
					}
					else if(pass.length() < Globals.MIN_PASS_LENGTH){
						errMsg.setText(R.string.pass_min);
					}
					else if(!pass.equals(pass2)){
						errMsg.setText(R.string.no_match);
					}
					else{
						try {
							String response = Globals.sendPostRequest("req_id=REGISTER&user="+login+"&pass="+pass+"&fb_url:"+fb);
							int code = Integer.parseInt(response.substring(0, response.indexOf(";")));
							String line = response.substring(response.indexOf(";") + 1);
							if(code == 200){
						        if(line.equals("OK")){
						        	Intent menu = new Intent(Register.this, MainMenu.class);
									menu.putExtra("username", login);
									menu.putExtra("level", "1");
									menu.putExtra("exp", "0");
									startActivity(menu);
									finish();
						        }
						        else{
						        	errMsg.setText(line);
						        	loginEdit.setText("");
						        }
							}
							else{
								errMsg.setText(R.string.server_err);
							}
						} catch(Exception ex){
							errMsg.setText(R.string.server_err);
						} 
					}
				} 
			}
		});
	}
}
